package domain.server;

import domain.Commands;
import domain.GameSettings;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Laurent Albessart
 * @version 2-jan-2012
 */
public class PlayerModel {

    private DatagramSocket datagramSocket;
    private Map<String, Player> players;

    public PlayerModel(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
        players = new HashMap<String, Player>();
    }

    public void sendMessageToAllPlayers(String msg) {
        //TODO update to send message to all relevant clients
        for (Player player : players.values()) {
            DatagramPacket outPacket = new DatagramPacket(msg.getBytes(), msg.length(), player.getIp(), player.getPort());
            try {
                datagramSocket.send(outPacket);
            } catch (IOException ex) {
                Logger.getLogger(PlayerModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public Map<String, Player> getPlayers() {
        return players;
    }

    public void addPlayer(String name, Player newPlayer) {
        players.put(name, newPlayer);
        //TODO send player which map
        sendMessageToPlayer(Commands.SETMAP + GameSettings.SEPARATOR + GameSettings.CURRENTMAP
                
                /*+ GameSettings.COMMANDSSPLIT + 
                
                Commands.TALK + GameSettings.SEPARATOR + "Please respect the rules."*/, newPlayer);
        sendMessageToAllPlayers(Commands.TALK + GameSettings.SEPARATOR + name + " has joined.");
    }

    public void removePlayer(String name) {
        players.remove(name);
        sendMessageToAllPlayers(Commands.TALK + GameSettings.SEPARATOR + name + " has left.");
    }

    public  void sendMessageToPlayer(String msg, Player player) {
        DatagramPacket outPacket = new DatagramPacket(msg.getBytes(), msg.length(), player.getIp(), player.getPort());
            try {
                datagramSocket.send(outPacket);
            } catch (IOException ex) {
                Logger.getLogger(PlayerModel.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
}
